/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.primitives.zip;

import java.util.zip.Deflater;
import java.util.zip.Inflater;

import fr.x9c.cadmium.kernel.Block;
import fr.x9c.cadmium.kernel.CodeRunner;
import fr.x9c.cadmium.kernel.Custom;
import fr.x9c.cadmium.kernel.Fail;
import fr.x9c.cadmium.kernel.Primitive;
import fr.x9c.cadmium.kernel.PrimitiveProvider;
import fr.x9c.cadmium.kernel.Value;

/**
 * Implements all primitives from 'zlibstubs.c'.
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
@PrimitiveProvider
public final class Zlib {

    /** Constant of <i>flush_command</i> type. */
    private static final Value Z_NO_FLUSH = Value.ZERO;

    /** Constant of <i>flush_command</i> type. */
    private static final Value Z_SYNC_FLUSH = Value.ONE;

    /** Constant of <i>flush_command</i> type. */
    private static final Value Z_FULL_FLUSH = Value.TWO;

    /** Constant of <i>flush_command</i> type. */
    private static final Value Z_FINISH = Value.createFromLong(3);

    /** CRC 32 table. */
    private static final int[] CRC_TABLE;

    /** Initialization of CRC table. */
    static {
        CRC_TABLE = new int[256];
        for (int i = 0; i < 256; i++) {
            int tmp = i;
            for (int j = 0; j < 8; j++) {
                if ((tmp & 1) != 0) {
                    tmp = 0xEDB88320 ^ (tmp >>> 1);
                } else {
                    tmp = tmp >>> 1;
                } // end if/else
                Zlib.CRC_TABLE[i] = tmp;
            } // end for
        } // end for
    } // end static block

    /**
     * No instance of this class.
     */
    private Zlib() {
    } // end empty constructor

    /**
     * Creates a deflater.
     * @param ctxt context
     * @param level compression level
     * @param header whether to use header
     * @return newly created deflater
     * @throws Fail.Exception <i>Zlib.Error</i> if an error occurs
     */
    @Primitive
    public static Value camlzip_deflateInit(final CodeRunner ctxt,
                                            final Value level,
                                            final Value header)
        throws Fail.Exception {
        try {
            return ZStream.create(new Deflater(level.asLong(),
                                               header == Value.FALSE),
                                  null);
        } catch (final Exception e) {
            error(ctxt, "Zlib.deflateInit", e);
            return Value.UNIT; // never reached
        } // end try/catch
    } // end method 'camlzip_deflateInit(CodeRunner, Value, Value)'

    /**
     * Exact synonym of {@link #camlzip_deflate_bytecode(fr.x9c.cadmium.kernel.CodeRunner, fr.x9c.cadmium.kernel.Value, fr.x9c.cadmium.kernel.Value, fr.x9c.cadmium.kernel.Value, fr.x9c.cadmium.kernel.Value, fr.x9c.cadmium.kernel.Value, fr.x9c.cadmium.kernel.Value, fr.x9c.cadmium.kernel.Value, fr.x9c.cadmium.kernel.Value)}.
     */
    @Primitive
    public static Value camlzip_deflate(final CodeRunner ctxt,
                                        final Value stream,
                                        final Value srcBuff,
                                        final Value srcPos,
                                        final Value srcLen,
                                        final Value dstBuff,
                                        final Value dstPos,
                                        final Value dstLen,
                                        final Value flush)
        throws Fail.Exception {
        return camlzip_deflate_bytecode(ctxt,
                                        stream,
                                        srcBuff,
                                        srcPos,
                                        srcLen,
                                        dstBuff,
                                        dstPos,
                                        dstLen,
                                        flush);
    } // end method 'camlzip_deflate(CodeRunner, Value, Value, Value, Value, ...)'

    /**
     * Deflates some data.
     * @param ctxt context
     * @param stream deflater
     * @param srcBuff source data buffer
     * @param srcPos position of data in source buffer
     * @param srcLen length of data in source buffer
     * @param dstBuff destination data buffer
     * @param dstPos position of data in destination buffer
     * @param dstLen length of data in destination buffer
     * @param flush flush command (only supports <i>Z_FINISH</i>)
     * @return <i>(end_of_stream, nb_read_from_source, nb_written_to_destination)</i>
     * @throws Fail.Exception <i>Zlib.Error</i> if an error occurs
     */
    @Primitive
    public static Value camlzip_deflate_bytecode(final CodeRunner ctxt,
                                                 final Value stream,
                                                 final Value srcBuff,
                                                 final Value srcPos,
                                                 final Value srcLen,
                                                 final Value dstBuff,
                                                 final Value dstPos,
                                                 final Value dstLen,
                                                 final Value flush)
        throws Fail.Exception {
        try {
            final Deflater d =
                ((ZStream) stream.asBlock().asCustom()).getDeflater();
            final long read = d.getBytesRead();
            d.setInput(srcBuff.asBlock().getBytes(),
                       srcPos.asLong(),
                       srcLen.asLong());
            if (flush == Z_FINISH) {
                d.finish();
            } // end if
            final int written = d.deflate(dstBuff.asBlock().getBytes(),
                                          dstPos.asLong(),
                                          dstLen.asLong());
            final Block res =
                Block.createBlock(0,
                                  d.finished() ? Value.TRUE : Value.FALSE,
                                  Value.createFromLong((int) (d.getBytesRead() - read)),
                                  Value.createFromLong(written));
            return Value.createFromBlock(res);
        } catch (final Exception e) {
            error(ctxt, "Zlib.deflate", e);
            return Value.UNIT; // never reached
        } // end try/catch
    } // end method 'camlzip_deflate_bytecode(CodeRunner, Value, Value, Value, ...)'

    /**
     * Closes a deflater
     * @param ctxt context
     * @param stream deflater to close
     * @return <i>unit</i>
     * @throws Fail.Exception <i>Zlib.Error</i> if an error occurs
     */
    @Primitive
    public static Value camlzip_deflateEnd(final CodeRunner ctxt,
                                           final Value stream)
        throws Fail.Exception {
        try {
            ((ZStream) stream.asBlock().asCustom()).getDeflater().end();
            return Value.UNIT;
        } catch (final Exception e) {
            error(ctxt, "Zlib.deflateEnd", e);
            return Value.UNIT; // never reached
        } // end try/catch
    } // end method 'camlzip_deflateEnd(CodeRunner, Value)'

    /**
     * Creates a inflater.
     * @param ctxt context
     * @param header whether to use header
     * @return newly created inflater
     * @throws Fail.Exception <i>Zlib.Error</i> if an error occurs
     */
    @Primitive
    public static Value camlzip_inflateInit(final CodeRunner ctxt,
                                            final Value header)
        throws Fail.Exception {
        try {
            return ZStream.create(null,
                                  new Inflater(header == Value.FALSE));
        } catch (final Exception e) {
            error(ctxt, "Zlib.inflateInit", e);
            return Value.UNIT; // never reached
        } // end try/catch
    } // end method 'camlzip_inflateInit(CodeRunner, Value)'

    /**
     * Exact synonym of {@link #camlzip_inflate_bytecode(CodeRunner, Value, Value, Value, Value, Value, Value, Value, Value)}.
     */
    @Primitive
    public static Value camlzip_inflate(final CodeRunner ctxt,
                                        final Value stream,
                                        final Value srcBuff,
                                        final Value srcPos,
                                        final Value srcLen,
                                        final Value dstBuff,
                                        final Value dstPos,
                                        final Value dstLen,
                                        final Value flush)
        throws Fail.Exception {
        return camlzip_inflate_bytecode(ctxt,
                                        stream,
                                        srcBuff,
                                        srcPos,
                                        srcLen,
                                        dstBuff,
                                        dstPos,
                                        dstLen,
                                        flush);
    } // end method 'camlzip_inflate(CodeRunner, Value, Value, Value, Value, ...)'

    /**
     * Inflates some data.
     * @param ctxt context
     * @param stream inflater
     * @param srcBuff source data buffer
     * @param srcPos position of data in source buffer
     * @param srcLen length of data in source buffer
     * @param dstBuff destination data buffer
     * @param dstPos position of data in destination buffer
     * @param dstLen length of data in destination buffer
     * @param flush ignored
     * @return <i>(end_of_stream, nb_read_from_source, nb_written_to_destination)</i>
     * @throws Fail.Exception <i>Zlib.Error</i> if an error occurs
     */
    @Primitive
    public static Value camlzip_inflate_bytecode(final CodeRunner ctxt,
                                                 final Value stream,
                                                 final Value srcBuff,
                                                 final Value srcPos,
                                                 final Value srcLen,
                                                 final Value dstBuff,
                                                 final Value dstPos,
                                                 final Value dstLen,
                                                 final Value flush)
        throws Fail.Exception {
        try {
            final Inflater i =
                ((ZStream) stream.asBlock().asCustom()).getInflater();
            final long read = i.getBytesRead();
            i.setInput(srcBuff.asBlock().getBytes(),
                       srcPos.asLong(),
                       srcLen.asLong());
            final int written = i.inflate(dstBuff.asBlock().getBytes(),
                                          dstPos.asLong(),
                                          dstLen.asLong());
            final Block res =
                Block.createBlock(0,
                                  i.finished() ? Value.TRUE : Value.FALSE,
                                  Value.createFromLong((int) (i.getBytesRead() - read)),
                                  Value.createFromLong(written));
            return Value.createFromBlock(res);
        } catch (final Exception e) {
            error(ctxt, "Zlib.inflate", e);
            return Value.UNIT; // never reached
        } // end try/catch
    } // end method 'camlzip_inflate_bytecode(CodeRunner, Value, Value, Value, ...)'

    /**
     * Closes a inflater
     * @param ctxt context
     * @param stream inflater to close
     * @return <i>unit</i>
     * @throws Fail.Exception <i>Zlib.Error</i> if an error occurs
     */
    @Primitive
    public static Value camlzip_inflateEnd(final CodeRunner ctxt,
                                           final Value stream)
        throws Fail.Exception {
        try {
            ((ZStream) stream.asBlock().asCustom()).getInflater().end();
            return Value.UNIT;
        } catch (final Exception e) {
            error(ctxt, "Zlib.inflateEnd", e);
            return Value.UNIT; // never reached
        } // end try/catch
    } // end method 'camlzip_inflateEnd(CodeRunner, Value)'

    /**
     * Updates a CRC32 value with some data.
     * @param crc <i>int32</i> CRC32 value
     * @param buff data buffer
     * @param pos position of data in buffer
     * @param len length of data in buffer
     * @return CRC32 value updated with passed data
     */
    @Primitive
    public static Value camlzip_update_crc32(final CodeRunner ctxt,
                                             final Value crc,
                                             final Value buff,
                                             final Value pos,
                                             final Value len) {
        int c = ~crc.asBlock().asInt32();
        final int l = len.asLong();
        final int ofs = pos.asLong();
        final byte[] b = buff.asBlock().getBytes();
        for (int i = 0; i < l; i++) {
            c = CRC_TABLE[(c ^ b[ofs + i]) & 0xFF] ^ (c >>> 8);
        } // end for
        final Block res = Block.createCustom(Custom.INT_32_SIZE,
                                             Custom.INT_32_OPS);
        res.setInt32(~c);
        return Value.createFromBlock(res);
    } // end method 'camlzip_update_crc32(CodeRunner, Value, Value, Value, Value)'

    /**
     * Raises a <i>Zlib.Error</i> exception.
     * @param ctxt context - should not be <tt>null</tt>
     * @param prim primitive raising exception - should not be <tt>null</tt>
     * @param e caught Java exception - should not be <tt>null</tt>
     * @throws Fail.Exception always
     */
    private static void error(final CodeRunner ctxt,
                              final String prim,
                              final Exception e)
        throws Fail.Exception {
        assert ctxt != null : "null ctxt";
        assert prim != null : "null prim";
        assert e != null : "null e";
        final Value camlzipException =
            ctxt.getContext().getCallback("Zlib.Error");
        if (camlzipException == null) {
            Fail.invalidArgument("Exception Zlib.Error not initialized");
        } else {
            final String msg = e.getMessage();
            final Block bucket =
                Block.createBlock(0,
                                  camlzipException,
                                  Value.createFromBlock(Block.createString(prim)),
                                  Value.createFromBlock(Block.createString(msg != null
                                                                           ? msg
                                                                           : "")));
            Fail.raise(Value.createFromBlock(bucket));
        } // end if/else
    } // end method 'error(CodeRunner, String, Exception)'

} // end class 'Zlib'
